/**
 * @license Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved.
 * For licensing, see LICENSE.md.
 */

/**
 * @module relFileSel/relFileSelUI
 */

import Plugin from '@ckeditor/ckeditor5-core/src/plugin';
import ButtonView from '@ckeditor/ckeditor5-ui/src/button/buttonview';
import relFileIcon from '../../theme/icons/relFile.svg';


const relKeystroke = 'Ctrl+R';
/**
 * The image upload button plugin.
 * Adds the `imageUpload` button to the {@link module:ui/componentfactory~ComponentFactory UI component factory}.
 *
 * @extends module:core/plugin~Plugin
 */
function getContextPath(){
	if(v3x){
		return v3x.baseURL ? v3x.baseURL: parent._ctxPath;
	}
	return '/seeyon';
}
function getEditorAssociate(){
	return '1,3';
}

var CsrfGuard = {
	getToken : function(){
		var token = typeof(CSRFTOKEN)==='undefined' ?  getA8Top().CSRFTOKEN :CSRFTOKEN;
		return typeof(token)==='undefined'|| token === 'null' ? '' : token;
	},
	isEnabled : function(){
		return this.getToken()!=='';
	},
	getUrlSurffix : function(url){
		if(typeof(url)!=='undefined' && url.indexOf('CSRFTOKEN=')>0){
			return '';
		}
		function getPrefix(url){
			var prefix = '&';
			if(typeof(url)!=='undefined'){
				if(url.indexOf('?')<0){
					prefix = '?';
				}
			}
			return prefix;
		}
		return !this.isEnabled() ? '' : getPrefix(url) + 'CSRFTOKEN='+this.getToken();
	},
	beforeAjaxSend: function(request) {
		var token_value = CsrfGuard.getToken();
		if(token_value!==''){
			request.setRequestHeader("X-Requested-With", "XMLHttpRequest");
			request.setRequestHeader( 'CSRFTOKEN', token_value);
		}
	}
};


var getContent=function (relDocLabel,uploadFileLabel,settingBtnLabel,settingBtnId,t) {
	return `
			<table align="left" role="presentation" style="width: 100%;" border="0" cellspacing="0">
				<tbody>
					<tr><td class="cke_dialog_ui_vbox_child" role="presentation">
						<div class="cke_dialog_ui_select" id="cke_61_uiElement clearfix" role="presentation">
							<label class="cke_dialog_ui_labeled_label pull-left" style="float:left;display:inline-block;font-size: 12px;height: 28px;line-height: 28px;min-width:55px;">${t( 'Link type' )}</label>
							<div class="cke_dialog_ui_labeled_content  pull-left" style="float:left;margin-left: 15px;">
								<div class="cke_dialog_ui_input_select" role="presentation">
									<select class="cke_dialog_ui_input_select" id="${settingBtnId}_select" style="height: 30px;line-height: 30px;width:100px;">
										<option value="1"> ${relDocLabel}<option value="3"> ${uploadFileLabel}</option>
									</select>
								</div>
							</div>
						</div></td>
					</tr>
					<tr><td class="cke_dialog_ui_vbox_child" role="presentation">
					<table class="cke_dialog_ui_hbox" id="cke_67_uiElement" role="presentation"><tbody>
					<tr class="cke_dialog_ui_hbox"><td class="cke_dialog_ui_hbox_first" role="presentation" style="width: 80%;padding-top:5px;">
					<div class="cke_dialog_ui_text clearfix" id="cke_64_uiElement" role="presentation" style="width: 100%;">
						<label class="cke_dialog_ui_labeled_label cke_required pull-left" style="float:left;display:inline-block;font-size: 12px;height: 28px;line-height: 28px;min-width:55px;">${t( 'Link' )}</label>
						<div class="cke_dialog_ui_labeled_content pull-left" style="float: left;margin-left: 12px;"><div class="cke_dialog_ui_input_text" role="presentation">
							<input id="${settingBtnId}_input" title="" class="cke_dialog_ui_input_text" style="height: 26px;padding:0px 6px;width:200px;" type="text" readonly="true">
							</div>
						</div></div></td>
					<td class="cke_dialog_ui_hbox_last" role="presentation" style="width: 25%; vertical-align: bottom;padding-left:3px;">
					<a title="${settingBtnLabel}" id="${settingBtnId}" class="cke_dialog_ui_button"  style="color:#000;padding:3px 15px;border-radius:18px;background: rgb(255, 255, 255); border: 1px solid rgb(209, 212, 219); 
					border-image: none; 
					height: 24px; line-height: 24px;" hidefocus="true" unselectable="on">
						<span class="cke_dialog_ui_button" style="font-size: 12px;display: inline-block;position: relative;top:-1px;">${settingBtnLabel}</span>
					</a></td></tr></tbody></table></td></tr>
				</tbody>
			</table>
`
}
var associates = [];
var seperator = '、';

function _getContent(){
	//循环相应的附件对象集合 组装相应的数据
	var backContent=[];var attachmentId ="";
	associates.forEach(function (item, index) {
		var v = [item.id,
			item.mimeType,
			item.description,
			item.reference,
			item.category,
			item.createDate,
			item.filename.replace(/\'/g,"\\'").replace(/\"/g,"&#034;"),
			item.v,
			'v_'+item.id+'_v'
		];
		var s = [];
		for (var j = 0; j < v.length; j++) {
			s.push("\'" + v[j] + "\'");
		};
		attachmentId = item.id;
		var attachmentIdStr = item.id ? ' attachmentId="'+item.id+'"' : '';
		var script = '<a class="'+attachmentId+'" href="javascript:if(typeof(openEditorAssociate)!=\'undefined\')' +
			'openEditorAssociate('+s.join(',')+');"' + attachmentIdStr +'>' + item.filename.escapeHTML() + '</a><a href="'+item.id+'">2</a>';
		backContent.push(script);
	});
	return {backContent:backContent,attachmentId:attachmentId};
}



export default class RelFileSelUI extends Plugin {

	//弹出附件上传窗口
	uploadFileDialog(divid){
		getA8Top().addCkEditor5Attachment=function(type, filename, mimeType, createDate, size, fileUrl, canDelete,needClone,x1,extension,icon,x2,x3,x4,v){
			var attachment = new Attachment(fileUrl, '', '', 1, type, filename, mimeType, createDate, size, fileUrl, '', '','','', '','',v);
			associates.push(attachment);

			var array=[];
			for ( var i = 0; i < associates.length; i++) {
				var att = associates[i];
				array.push(att.filename);
			}
			getA8Top().$("#"+divid+"_input").val(array.join(seperator));
		}

		var url = getContextPath()+'/fileUpload.do?type=0&applicationCategory=1&extensions=&maxSize=&isEncrypt=true&popupTitleKey=&isA8geniusAdded=false&quantity=5&callback=addCkEditor5Attachment&firstSave=true'+ CsrfGuard.getUrlSurffix();
		getCtpTop().addattachDialog = null;
		getCtpTop().addattachDialog = getCtpTop().$.dialog({
			title: $.i18n("fileupload.page.title"),
			transParams:{'parentWin':getA8Top()},
			url   : url,
			width : 400,
			height  : 250
		});
	}

	//弹出关联文档选择窗口
	insertCorrelationFile(divid){
		//重写顶层回调函数
		getA8Top().updateAssociateUrl=function(atts){
			associates=atts;
			if(atts!=null){
				var array = [];
				for ( var i = 0; i < atts.length; i++) {
					var att = atts[i];
					array.push(att.filename);
				}
				getA8Top().$("#"+divid+"_input").val(array.join(seperator));
			}
		}
		/**
		 * 打开关联文档对话框
		 */
		if(v3x.getBrowserFlag('OpenDivWindow')==true){
			getCtpTop().addassDialog = null;
			getCtpTop().addassDialog = getCtpTop().$.dialog({
				title: $.i18n("common.mydocument.label"),
				transParams:{'parentWin':getA8Top(),'divid':divid },
				url   : getContextPath() + '/ctp/common/associateddoc/assdocFrame.do?callMethod=updateAssociateUrl&poi=99&isBind=' + getEditorAssociate() + CsrfGuard.getUrlSurffix(),
				width : 800,
				height  : 600
			});
		}
	}
	//弹出关联总窗口 在这里面选择相应的选项
	showRelFileSelPage(){
		const editor = this.editor;
		const t = editor.t;
		const btnId='relDocSettingBtn';
		associates=[];

		var dialog = $.dialog({
			id: 'saveAsTemplate',
			html: "<div style='padding: 10px 20px;'>"+getContent(t( 'Associate document' ),t( 'Upload attachement' ),t( 'set up' ),btnId,t)+"</div>",
			width: 440,
			height: 180,
			title: t( 'Insert rel file' ),  // 另存为个人模板
			buttons: [{
				text: $.i18n('collaboration.pushMessageToMembers.confirm'), // 确定
				handler: function () {

					//获取需要回填的内容
					var backContentJosn=_getContent();
					// var backContent=backContentJosn["backContent"];
					editor.execute( 'insertRelFile',backContentJosn);
					dialog.close();
				}
			}, {
				text: $.i18n('collaboration.pushMessageToMembers.cancel'), // 取消
				handler: function () {
					dialog.close();
				}
			}]
		});
        //注册设置按钮的点击事件
		var obj=this;
		getA8Top().$("#"+btnId).click(function () {
			associates=[];
			 var selValue=getA8Top().$("#"+btnId+"_select").find("option:selected").val();
			// 1表示选择的是关联文档  3 表示选择的是上传附件
			if (selValue+"" === "1") {
				obj.insertCorrelationFile(btnId);
			}else if (selValue+"" === "3") {
				obj.uploadFileDialog(btnId);
			}
		})
	}
	/**
	 * @inheritDoc
	 */
	init() {
		const editor = this.editor;
		const t = editor.t;

		// Setup `imageUpload` button.
		editor.ui.componentFactory.add( 'relFileSel', locale => {
			const button = new ButtonView( locale );

			button.isEnabled = true;
			button.label = t( 'Insert rel file' );
			button.icon = relFileIcon;
			button.keystroke = relKeystroke;
			button.class="relFileSel";
			button.tooltip = true;

			// Show the panel on button click.
			this.listenTo( button, 'execute', () => {
				 this.showRelFileSelPage();
			});

			return button;
		} );
	}
}
